#coding=utf-8
__author__ = 'jiangning'

from django.forms import ModelForm
from django import forms
from django.contrib.auth.models import User
from .models import Question
from  DjangoUeditor.widgets import UEditorWidget
from  DjangoUeditor.forms import UEditorField

class MyCreateUserForm(ModelForm):
    error_messages ={
        "duplicate_username":u'用户名已经存在!',
        "check_password":u'您输入的两次密码不一致!',
        "duplicate_email":u'email已经存在'
    }

    username = forms.RegexField(max_length=30,regex=r'^[\w.@+-]+$',
            error_messages={
            'invalid':  u"该值只能包含字母、数字和字符@/./+/-/_",
            'required': u"用户名未填"
            })
    email = forms.EmailField(error_messages={
        'invalid':  u"email格式错误",
        'required': u'email未填'})

    password = forms.CharField(widget=forms.PasswordInput,
        error_messages={
            'required': u"密码未填"
            })

    password2 = forms.CharField(widget=forms.PasswordInput,
        error_messages={
            'required': u"确认密码未填"
            })
    class Meta:
        model = User
        fields = ('username','password',)

    def clean_username(self):
        username = self.cleaned_data['username']
        try:
            User._default_manager.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(
            self.error_messages['duplicate_username']
        )

    def clean_password2(self):
        password = self.cleaned_data['password']
        password2 = self.cleaned_data['password2']
        if password and password2 and password != password2:
            raise forms.ValidationError({
                self.error_messages['check_password']
            })

    def clean_email(self):
        email = self.cleaned_data["email"]

        #判断是这个email 用户是否存在
        try:
            User._default_manager.get(email=email)
        except User.DoesNotExist:
            return email
        raise forms.ValidationError(
            self.error_messages["duplicate_email"]
        )

    def save(self, commit=True):
        user = super(MyCreateUserForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password"])
        if commit:
            user.save()
        return user

class QuestionForm(forms.Form):
    # title = forms.CharField(max_length=200)
    content=UEditorField(u'',width=680,height=800)
    # class Meta:
    #     model = Question
    #     fields = ('title','content','questioner')

# class QuestionForm(forms.Form):
#
#     Content=UEditorField("描述",initial="abc",width=600,height=800)


# class AskForm(forms.ModelForm):
#     content = forms.CharField(widget=CKEditorWidget())
#     class Meta:
#         model = Ask


